package translate;

import temp.Label;
import tree.BasicExp;
import tree.CALL;
import tree.ExpList;
import tree.MEM;
import tree.NAME;
import tree.TEMP;
import util.BoolList;

public class CallExp extends Ex {
	public int inFrameCnt = 0;
	ExpList head = null, tail = null;
	ExpList sLink = null;
	BoolList inFrame = null;
	Label lab;

	public CallExp(temp.Label l, Level e) {
		super(null);
		lab = l;
		BoolList tail = null;
		for (AccessList al = e.formals; al != null; al = al.tail) {
			if (inFrame == null)
				tail = inFrame = new BoolList((al.head.acc instanceof mips.InFrame), null);
			else
				tail = tail.tail = new BoolList((al.head.acc instanceof mips.InFrame), null);
			if (tail.head) inFrameCnt++;
		}
	}

	public void calcStaticLink(Level caller, Level callee) {
		Level cr = caller, ce = callee;
		BasicExp stle = new TEMP(caller.frame.FP());

		while (cr.depth > ce.depth) {
			stle = new MEM(stle);
			cr = cr.parent;
		}
		if (cr.depth == ce.depth) stle = new MEM(stle); 
		sLink = new ExpList(stle, head);
	}

	public void addArg(Exp e) {
		if (head == null)
			tail = head = new ExpList(e.unEx(), null);
		else {
			tail.tail = new ExpList(e.unEx(), null);
			tail = tail.tail;
		}
	}

	public BasicExp unEx() {
		return new CALL(new NAME(lab), sLink);
	}
}
